package com.fgchen.util.excel;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;

/**
 * Created by Administrator on 2018-04-09.
 */
public class ExcelUtil {

    public static Workbook getWorkbook(ExcelConfig excelConfig) throws Exception {
        InputStream inputStream = ExcelUtil.class.getClassLoader().getResourceAsStream(excelConfig.getTemplate());
        Workbook workbook = null;
        try {
            workbook = new HSSFWorkbook(inputStream);
        } catch (Exception e) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return  workbook;
    }

    public static <T> void generateRow(T entity, Row row, ExcelConfig excelConfig) throws Exception {
        for (Column column : excelConfig.getColumns()) {
            String value = PropertyUtils.getProperty(entity, column.getProperty()).toString();
            row.createCell(column.getColumn()).setCellValue(value);
        }
    }

}
